package com.pwt.controller.permission;

import com.pwt.common.CustomException;
import com.pwt.common.DataNotFoundException;
import com.pwt.model.UserLoginModel;
import com.pwt.model.UserModel;
import com.pwt.model.UserPOJO;
import com.pwt.security.UserDetailsServiceImpl;
import com.pwt.service.UserService;
import com.pwt.utils.HttpUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Tag(name = "用户登录接口")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    UserDetailsServiceImpl userDetailsService;



    @PostMapping("login")
    @Operation(description = "用户登录")
    public void login(@RequestBody @Validated UserLoginModel userAddModel) {
        // 此方法为标记swagger, 实际已被filter拦截, 代码逻辑在
        // com.pwt.security.JWTLoginFilter attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
        // 和
        // com.pwt.security.UserDetailsServiceImpl loadUserByUsername(String username)
    }

    @GetMapping("profile")
    @Operation(description = "查询个人信息")
    public UserPOJO profile() throws DataNotFoundException {
        return userService.profile();
    }


    @GetMapping("token")
    @Operation(description = "根据用户获取token")
    public String loginByName(String username) {
        return userDetailsService.getToken(username);
    }

    @GetMapping("/ssologin")
    public Map<String,Object> ssoLogin(@RequestParam("ticket") String ticket, HttpServletResponse response) throws CustomException, IOException {
        Map<String,Object> map =new HashMap<>();
        if(ticket==null||"".equals(ticket)){
            map.put("code",500);
            map.put("msg","参数非法");
            map.put("data","");
        }else {
            // 根据 ticket 获取用户名的接口地址
            String getLoginNameUrl = "http://10.0.108.11:35380/seeyon/thirdpartyController.do?ticket=" + ticket;
            String username = HttpUtils.doGet(getLoginNameUrl).trim();
            if (username != null && !"".equals(username)) {
                this.userService.add(username);
                map.put("code", 200);
                map.put("msg", "单点登录成功");
                map.put("data", username);
                response.sendRedirect("http://10.0.108.11:32399/#/home?username="+username);
            } else {
                map.put("code", 500);
                map.put("msg", "单点登录失败");
                map.put("data", "");
                response.sendRedirect("http://10.0.108.11:32399/#/index");
            }
        }

        return map;
    }

}
